<?php

/**
 * Created by PhpStorm.
 * User: Jacky Yu
 * Date: 2017/3/22
 * Time: 10:04
 */
class User_model extends CI_Model
{
    var $_table_name = 'user';

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('cookie');
        $this->load->library('wechatapi/WxSDK');
    }

    //获得用户信息
    public function get_user_info()
    {

        /**三个途径获取用户信息：
         * 1、cookie；
         * 2、非微信生成用户标识，缓存到cookie；
         * 3、微信接口获取用户信息，缓存到cookie；
         **/
        if (get_cookie('user_openid')) {
            return get_cookie('user_openid');
        } else {
            //$user_openid = WxSDK::is_broswer() ? $this->_wechat_user_info() : $this->_generate_user_info();
            $user_openid = $this->_generate_user_info();//暂时屏蔽通过微信获取用户信息
            set_cookie('user_openid', $user_openid, '604800');
            return $user_openid;
        }
    }

    //从微信获取用户信息
    private function _wechat_user_info()
    {
        $current_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER["REQUEST_URI"];
        $user_info = WxSDK::getUserInfo($current_url, false);
        return $user_info['openid'];
    }

    //非微信环境生成虚拟用户数据
    private function _generate_user_info()
    {
        $this->load->helper('string');
        return random_string('alpha', 4) . time();
    }

}